import React from 'react'
import { connect } from 'react-redux'
import {messages} from "share/common";
import menuRoute from 'routes/menuRoute';
import {Button, Alert} from 'antd';
import CityGroupService from 'containers/setting/city-group/city-group.service';
import 'styles/setting/city-group/city-group-info/city-group-detail.scss';
import SearchArea from "components/search-area";
import config from "config";
import ResizeTable from "components/resize-table";

class CityGroupAddCity extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      addLoading: false,
      allLoading: false,
      data: [],
      columns: [
        {title: messages('setting.key2027')/*已分配城市组*/, width: '16%', dataIndex: 'level.levelName'},
        {title: messages('setting.key190'/*国家*/), dataIndex: 'country'},
        {title: messages('setting.key2028')/*地点名称*/, dataIndex: 'vendorAlias'},
        {title: messages('setting.key2029')/*地点编码*/ /* 国家*/, dataIndex: 'code'},
        {title: messages('setting.key2030')/*地点类型*/, width: '7%', dataIndex: 'typeName'},
        {title: messages('setting.key2031')/*地点级别*/, width: '7%', dataIndex: 'levelId'},
        {title: messages('setting.key2032')/*路径*/, dataIndex: 'path'},
      ],
      searchParams: {
        continentCode: "",
        countryCode: "",
        typeCode: "",
        levelId: "",
        name: "",
        path: "",
      },
      searchForm: [
        {
          type: 'select',
          id: 'continentCode',
          label: messages('setting.key2033')/*洲际*/,
          options: [],
          method: 'get',
          valueKey: 'code',
          labelKey: 'messageKey',
          getParams: {roleType: 'TENANT'},
          getUrl: `${config.baseUrl}/api/custom/enumeration/items/by/template/type?systemCustomEnumerationType=20009&keyword=`
        },
        {
          type: 'selector',
          id: 'countryCode',
          label: messages('basic-data.key5'/*国家*/),
          selectorType: 'newCountry',
          showSearch: true
        },
        {
          type: 'select',
          id: 'typeCode',
          label: messages('setting.key2030')/*地点类型*/,
          options: [],
          method: 'get',
          valueKey: 'code',
          labelKey: 'description',
          getParams: {roleType: 'TENANT'},
          getUrl: `${config.baseUrl}/api/areas/type/list`
        },
        {
          type: 'select',
          id: 'levelId',
          label: messages('setting.key2031')/*地点级别*/,
          options: [{label: 1, value: 1}, {label: 2, value: 2}, {label: 3, value: 3}, {label: 4, value: 4},],
          valueKey: 'value',
          labelKey: 'label',
        },
        {type: 'input', id: 'name', label: messages('setting.key2028')/*地点名称*/},
        {type: 'input', id: 'path', label: messages('setting.key2034')/*路径名称*/}
      ],
      page: 0,
      pageSize: 10,
      pagination:{
        total: 0,
        page: 0,
        pageSize: 10,
      },
      selectedRowKeys: [],//列表里选中的列
      record: {},//选择某一行进行编辑时的当前行
      levelOID: this.props.levelOID,
      cityGroupDetail: menuRoute.getRouteItem('city-group-info','key').url,//详细信息页面
    };
  }

  //默认显示中国
  componentWillMount () {
    this.searchCity();
  };

  componentWillReceiveProps (nextProps) {
    if(nextProps.activeKey === messages('setting.key194'/*添加城市*/)){
      this.searchCity();
    }
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys, e) => {
    this.setState({
      selectedRowKeys,
    })
  };

  //点击搜索按钮
  onSearch = (result) => {
    let {pagination} = this.state;
    pagination.page = 0;
    pagination.pageSize = 10;
    this.setState({
      searchParams: result,
      pagination,
    }, () => {
      this.searchCity()
    })
  };

  //搜索城市
  searchCity = () => {
    const {searchParams} = this.state;
    let {pagination} = this.state;
    this.setState({
      loading: true,
    });
    CityGroupService.newSearchCity(searchParams, pagination.page).then(res => {
        if(res.status === 200){
          pagination.total = Number(res.headers['x-total-count']);
          pagination.current = this.state.pagination.page + 1;
          this.setState({
            data: res.data,
            loading: false,
            pagination,
          });
        }
      }).catch(err => {
      this.setState({
        loading: false,
      })
    })
  };

  //添加城市
  addCity = (e, bool) => {
    const {selectedRowKeys, levelOID, cityGroupDetail, searchParams} = this.state;
    let params = {};
    if(bool){
      params = Object.assign(searchParams, {levelOID, selectType: "ALL",})
      this.setState({
        allLoading: true,
      });
    }else{
      params = {levelOID, areaCodes: selectedRowKeys};
      this.setState({
        addLoading: true,
      });
    }
    CityGroupService.addCity(params).then(res => {
        this.setState({
          addLoading: false,
          allLoading: false,
          selectedRowKeys: [],
        });
        this.context.router.push(cityGroupDetail.replace(':levelOID', levelOID));
        this.props.parentMessage("添加成功");
    }).catch(err => {
      this.setState({
        addLoading: false,
        allLoading: false,
      });
      this.props.parentMessage("添加失败");
    })
  };

  //分页点击
  onTableChange = (pagination1) => {
    let { pagination} = this.state;
    pagination.page = pagination1.current - 1;
    pagination.pageSize = pagination1.pageSize;
    pagination.total = pagination1.total;
    this.setState({
      pagination,
    }, () => {
      this.searchCity();
    });
  };

  //点击重置
  clear = () => {
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.total = 0;
    this.setState({
      pagination,
      searchParams: {
        continentCode: "",
        countryCode: "",
        typeCode: "",
        levelId: "",
        name: "",
        path: "",
      },
    }, () => {
      this.searchCity();
    })
  };

  render () {
    const {data, columns, pagination, selectedRowKeys, loading, allLoading, addLoading, searchForm} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,//去掉默认的
    };

    return(
      <div className={'city-group-info-detail'}>
        <div>
          <SearchArea searchForm={searchForm} submitHandle={this.onSearch} clearHandle={this.clear}/>
        </div>
        <br/>
        <Alert
          message={messages('setting.key2149')/*注意：每次搜索最多返回1000条地点结果*/}
          description={messages('setting.key2150')/*每次最多可添加1000个地点POI*/}
          type="info"
          showIcon
        />
        <br/>
        <div>
          <Button type={'primary'} ghost onClick={(e) => this.addCity(e, true)} loading={allLoading} style={{marginRight: 15}}> {messages('setting.key2035')/*添加全部城市*/}
          </Button>
          <Button type={'primary'} onClick={(e) => this.addCity(e, false)} disabled={!selectedRowKeys.length} loading={addLoading}> {messages('setting.key2036')/*添加已勾选城市*/}
          </Button>
        </div>
        <br/>
        <div>
          <ResizeTable
            bordered
            rowClassName={"no-hover-style"}
            rowKey={'code'}
            loading={loading}
            size={'middle'}
            dataSource={data}
            columns={columns}
            pagination={pagination}
            onChange={this.onTableChange}
            rowSelection={rowSelection}
          />
        </div>
      </div>
    )
  };
}

CityGroupAddCity.contextTypes = {
  router: React.PropTypes.object,
};

CityGroupAddCity.propTypes = {
  parentMessage: React.PropTypes.any,  //传到父组件
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(CityGroupAddCity);
